package com.gking.resourcePool.filter;


import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * 为了读取请求中的 body 参数
 */
@WebFilter(urlPatterns = "/*")
public class HttpServletRequestReplacedFilter implements Filter {

    private boolean check(String requestURI) {
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/resource/upload",
                "/resource/upload/**",
                "/public/**",
        };
        //路径匹配器，支持通配符
        AntPathMatcher PATH_MATCHER = new AntPathMatcher();

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if (check(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        ServletRequest servletWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            servletWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
        }
        if (servletRequest == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            try {
                filterChain.doFilter(servletWrapper, servletResponse);
            } catch (IOException | ServletException e) {
                e.printStackTrace();
            }
        }
    }
}


class RequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    private byte[] readBody(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        return outputStream.toByteArray();
    }

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = readBody(request.getInputStream());
    }


    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return bais.read();
            }
        };
    }
}
